package com.bblocks.auth.support.service.impl;


import com.bblocks.auth.support.service.UpmsUserDetailsService;
import com.bblocks.enums.AppTypeEnum;
import com.bblocks.enums.CodeTypeEnum;
import com.bblocks.enums.LoginTypeEnum;
import com.bblocks.enums.SysEnum;
import com.bblocks.pojo.ComUser;
import com.bblocks.sms.service.SmsCheckCodeService;
import com.bblocks.util.R;
import com.pig4cloud.pig.admin.api.dto.UserInfo;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.stereotype.Service;

/**
 * upms 手机号提取用户详细信息
 * @author aeizzz
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UpmsMobileUserDetailServiceImpl extends UpmsUserDetailsService {

	private final UserDetailsService pigxDefaultUserDetailsServiceImpl;

	private final RemoteUserService remoteUserService;

	private final SmsCheckCodeService smsCheckCodeService;

	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {
		R<UserInfo> result = remoteUserService.infoByMobileInner(phone);
		return getUserDetails(result);
	}

	@Override
	public UserDetails loadUserByUser(ComUser pigxUser) {
		return pigxDefaultUserDetailsServiceImpl.loadUserByUsername(pigxUser.getUsername());
	}

	/**
	 * 支持所有的 mobile 类型
	 * @param clientId 目标客户端
	 * @param grantType 授权类型
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType, AppTypeEnum apptype) {
		return  LoginTypeEnum.Sms.getName().equals(grantType) && (apptype == null || this.appType() == apptype);
	}

	/**
	 *  验证码校验（2个方案）
	 *  1、共享redis进行操作（本处用此方案）
	 *  2、提供远程接口
	 * @param userDetails
	 * @param authentication
	 * @param messages 国际化消息
	 */
	public void check(UserDetails userDetails,
					   UsernamePasswordAuthenticationToken authentication
			, MessageSourceAccessor messages){
		if (authentication.getCredentials() == null) {
			throw new BadCredentialsException(messages
					.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
		}
		String mobile = authentication.getPrincipal().toString();
		String code = authentication.getCredentials().toString();

		SysEnum ret = smsCheckCodeService.chkCode(mobile,code, CodeTypeEnum.CodePub,false);
		if(SysEnum.SUCCESS != ret){
			throw new OAuth2AuthenticationException(ret.getMessage());
		}
	}

}
